package com.example.maggie.meizinote.mvp.presenter;

import android.app.Application;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.maggie.meizinote.R;
import com.example.maggie.meizinote.app.MApp;
import com.example.maggie.meizinote.app.bean.ClassifyBean;
import com.example.maggie.meizinote.app.bean.note_item;
import com.example.maggie.meizinote.mvp.listener.NoteClassifyListener;
import com.example.maggie.meizinote.mvp.ui.activity.HomeActivity;
import com.example.maggie.meizinote.mvp.ui.activity.LoginActivity;
import com.example.maggie.meizinote.mvp.ui.activity.NoteEditActivity;
import com.example.maggie.meizinote.mvp.ui.adapter.HomeMenuAdapter;
import com.example.maggie.meizinote.mvp.ui.adapter.NoteListAdapter;
import com.example.maggie.meizinote.mvp.ui.widget.YesOrNoDialog;
import com.jess.arms.base.delegate.IFragment;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.example.maggie.meizinote.mvp.contract.HomeContract;

import java.util.Arrays;
import java.util.List;


@ActivityScope
public class HomePresenter extends BasePresenter<HomeContract.Model, HomeContract.View>
        implements BaseQuickAdapter.OnItemClickListener, NoteClassifyListener
        , BaseQuickAdapter.OnItemLongClickListener, View.OnClickListener
        , BaseQuickAdapter.OnItemChildClickListener {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    public String classifyId = "";

    @Inject
    public HomePresenter(HomeContract.Model model, HomeContract.View rootView) {
        super(model, rootView);
    }

    public void toLogin() {
        mRootView.launchActivity(new Intent(mApplication, LoginActivity.class));
        mRootView.killMyself();
    }

    public void getData() {
        BmobQuery<note_item> query = new BmobQuery<note_item>();
        //返回50条数据，如果不加上这条语句，默认返回10条数据
        query.addWhereEqualTo("user_id", MApp.getUserId());
        if (classifyId != null && !classifyId.trim().isEmpty())
            query.addWhereEqualTo("classify_id", classifyId);
        query.setLimit(500);
        //执行查询方法
        query.findObjects(new FindListener<note_item>() {
            @Override
            public void done(List<note_item> object, BmobException e) {
                if (e == null) {
                    mRootView.addData(object);
                } else {
                    Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    public void getClassifyData() {
        BmobQuery<ClassifyBean> query = new BmobQuery<ClassifyBean>();
        //返回50条数据，如果不加上这条语句，默认返回10条数据
        query.addWhereEqualTo("user_id", MApp.getUserId());
        query.addWhereEqualTo("is_del", false);
        query.setLimit(500);
        //执行查询方法
        query.findObjects(new FindListener<ClassifyBean>() {
            @Override
            public void done(List<ClassifyBean> object, BmobException e) {
                if (e == null) {
                    mRootView.setClassifyData(object);
                } else {
                    Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    public void addClassify(String title) {
        ClassifyBean p = new ClassifyBean();
        p.setTitle(title);
        p.setUser_id(MApp.getUserId());
        p.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    getClassifyData();
                } else {
                    mRootView.showMessage("保存失败：" + e.getMessage());
                }
            }
        });
    }

    public void updataClassify(String title, String id) {
        ClassifyBean p = new ClassifyBean();
        p.setTitle(title);
        p.setUser_id(MApp.getUserId());
        p.update(id, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                getClassifyData();
            }
        });
    }

    public void delectClassify(ClassifyBean item) {
        if (item == null) return;
        item.setUser_id(MApp.getUserId());
        item.delete(new UpdateListener() {

            @Override
            public void done(BmobException e) {
                getClassifyData();
            }
        });
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof NoteListAdapter)
            //进入详情页
            mRootView.launchActivity(new Intent(mApplication, NoteEditActivity.class)
                    .putExtra("note", (note_item) adapter.getItem(position))
            );
        if (adapter instanceof HomeMenuAdapter) {
            //修改筛选条件，并刷新列表数据
            classifyId = ((ClassifyBean) adapter.getItem(position)).getObjectId();
            getData();
        }
    }

    public void addClassifybefore(String name, String id) {
        BmobQuery<ClassifyBean> query = new BmobQuery<ClassifyBean>();
        query.addWhereEqualTo("user_id", MApp.getUserId());
        query.addWhereEqualTo("title", name);
        query.setLimit(1);
        query.findObjects(new FindListener<ClassifyBean>() {
            @Override
            public void done(List<ClassifyBean> list, BmobException e) {
                if (e == null) {
                    if (list.size() == 0)
                        if (id != null && !id.trim().isEmpty())
                            updataClassify(name, id);
                        else
                            addClassify(name);
                    else mRootView.showMessage("已有同名目录");
                } else {
                    Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });

    }

    @Override
    public void add(Dialog dialog, int a, String name, String id) {
        if (name != null && !name.trim().isEmpty())
            addClassifybefore(name, id);
        else mRootView.showMessage("名字不能为空");
        dialog.dismiss();
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof NoteListAdapter) {
            //更多操作
            // 1.删除
            // 2.更换分组
        }
        if (adapter instanceof HomeMenuAdapter) {
            if (position == 0) return false;//0为全部   不做操作
            //目录长按重命名
            ClassifyBean cb = (ClassifyBean) adapter.getItem(position);
            if (!(cb.getObjectId() == null || cb.getObjectId().trim().isEmpty()))
                mRootView.showClassifyEditDialog(cb.getTitle(), cb.getObjectId());
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.logout:
                MApp.setUserId(new BmobUser());
                toLogin();
                break;
            case R.id.add_note_classify:
                mRootView.showClassifyEditDialog("", "");//新建的无数据
                break;
            case R.id.day_or_night:
                MApp.isNight = !MApp.isNight;//夜间切换
                if (MApp.isNight) ((TextView) view).setText("日间模式");
                else ((TextView) view).setText("夜间模式");
                mRootView.dayOrNight();
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (view.getId() == R.id.menu_delect)
            mRootView.showClassifyDelectDialog((ClassifyBean) adapter.getItem(position));
    }
}
